import java.io.*;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        String serverAddress = "120.55.190.147"; // 服务器IP地址
        int port = 8080; // 服务器端口号
        String imagePath = "C:/Users/98301/Desktop/fsdownload/故障图.jpg"; // 本地主机图片路径

        try (Socket socket = new Socket(serverAddress, port);
             FileInputStream fis = new FileInputStream(imagePath);
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {

            // 读取图片文件并发送给服务器
            File imageFile = new File(imagePath);
            dos.writeLong(imageFile.length()); // 发送图片大小
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
            }
            dos.flush();

            // 接收服务器返回的检测结果图片和JSON文件
            DataInputStream dis = new DataInputStream(socket.getInputStream());

            // 保存检测结果图片
            long resultImageSize = dis.readLong();
            FileOutputStream fosImage = new FileOutputStream("detected_image.jpg");
            byte[] imageBuffer = new byte[4096];
            int imageBytesRead;
            while (resultImageSize > 0 && (imageBytesRead = dis.read(imageBuffer, 0, (int)Math.min(imageBuffer.length, resultImageSize))) != -1) {
                fosImage.write(imageBuffer, 0, imageBytesRead);
                resultImageSize -= imageBytesRead;
            }
            fosImage.close();

            // 保存JSON文件
            long jsonFileSize = dis.readLong();
            FileOutputStream fosJson = new FileOutputStream("result.json");
            byte[] jsonBuffer = new byte[4096];
            int jsonBytesRead;
            while (jsonFileSize > 0 && (jsonBytesRead = dis.read(jsonBuffer, 0, (int)Math.min(jsonBuffer.length, jsonFileSize))) != -1) {
                fosJson.write(jsonBuffer, 0, jsonBytesRead);
                jsonFileSize -= jsonBytesRead;
            }
            fosJson.close();

            System.out.println("检测结果已保存。");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

